package NWPackage;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class TransitiveClosure {
	private static List<PairPreferdCandidateCell> allCellsFound;
	
	public static List<PairPreferdCandidateCell> getClosure(List<PairPreferdCandidateCell> agentQueries){
		allCellsFound = new ArrayList<PairPreferdCandidateCell>();
		
		for (PairPreferdCandidateCell cell : agentQueries) {
			String[] candidates = cell.getCandidatesByPrefferedOrder();
			dfs(agentQueries,candidates[0],candidates[1]);
			//allCellsFound.add(new PairPreferdCandidateCell(cell.getAgentName(),candidates[0],candidates[1],candidates[1]));
		}
		RemoveDuplicates();
		return allCellsFound;
	}
	
	private static void dfs(List<PairPreferdCandidateCell> G, String c1,String c2) {
		List<PairPreferdCandidateCell> c2List = getList(G,c2);
		for (PairPreferdCandidateCell cell : c2List)
		{
			String[] candidates = cell.getCandidatesByPrefferedOrder();
			dfs(G,c1,candidates[1]);
			PairPreferdCandidateCell newCell = new PairPreferdCandidateCell(cell.getAgentName(),c1,candidates[1],candidates[1]);
			if (!G.contains(newCell))
				allCellsFound.add(newCell); 
		}
	}

	private static List<PairPreferdCandidateCell> getList(
			List<PairPreferdCandidateCell> G, String c2) {

		List<PairPreferdCandidateCell> newList = new ArrayList<PairPreferdCandidateCell>();
		for (PairPreferdCandidateCell cell : G) {
			String[] candidates = cell.getCandidatesByPrefferedOrder();
			if (candidates[0] == c2)
				newList.add(cell);
		}
		return newList;
	}
	
	//after we finish with the transitive closure alg.
	//we are sometimes find the same query from 2 or more different pairs.
	private static void RemoveDuplicates() {
		
		List<PairPreferdCandidateCell> tempList = new ArrayList<PairPreferdCandidateCell>();
		Iterator<PairPreferdCandidateCell> it = allCellsFound.iterator();
		while (it.hasNext())
		{
			PairPreferdCandidateCell cell = (PairPreferdCandidateCell)it.next();
			if (!tempList.contains(cell)) tempList.add(cell);
		}
		
		allCellsFound.clear();
		allCellsFound.addAll(tempList);
	}
	
}
